package aiku.numericalcontroloa.Base.Utils;

import aiku.numericalcontroloa.Mapper.UserMapper;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * @Description 切面日志打印
 * @Date 2022/1/7 15:26
 * @Created by LSH
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    private final UserMapper userMapper;


    // 构造器注入
    public LogAspect(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 定义切点
     */
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && execution(* *(..))")
    public void doAspect() {
    }

    @Around("doAspect()")
    public Object doAround(ProceedingJoinPoint pjd) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = null;
        String handleUUID = "";

        if (!StpUtil.isLogin()) {
            handleUUID = "未登录";
        } else {
            String nickName = userMapper.selectById(StpUtil.getLoginId().toString()).getNickName();
            if (nickName == null || nickName.isEmpty()){
                handleUUID = "微信用户";
            }else {
                handleUUID = nickName;
            }
        }

        try {
            // 拦截的类
            Class<?> clazz = pjd.getTarget().getClass();
            // 拦截的方法
            Method method = ((MethodSignature) pjd.getSignature()).getMethod();
            String params = "";

            // 方法开始前打印日志
            if (method != null) {
                params = Arrays.toString(pjd.getArgs());
                LogUtils.startInfo(log, method.getName(), clazz.getName(), handleUUID, params);
            }

            // 执行拦截的方法
            result = pjd.proceed();

            // 方法结束后打印返回结果
            if (method != null) {
                LogUtils.endInfo(log, method.getName(), clazz.getName(), handleUUID, result, System.currentTimeMillis() - startTime);
            }

        } catch (Throwable e) {
            throw e;
        }
        return result;
    }
}
